﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using Vanfa.Entities.User;
using Vanfa.Biz.User;

namespace Vanfa.Web.ajax
{
    /// <summary>
    /// UserAjaxHandler 的摘要说明
    /// </summary>
    public class UserAjaxHandler : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            var call = context.Request["call"];
            switch (call)
            {
                case "code":
                    Render(SendCheckCode(context.Request["mobile"]), context);
                    break;
                case "login":
                    var lret = UserLogin(context.Request["user"], context.Request["pwd"], context);
                    Render(lret, context);
                    break;
                default:
                    break;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string SendCheckCode(string mobile)
        {
            var c = UserMag.CreateCode(mobile);
            //To 调用sms接口
            return c;
        }

        private string UserLogin(string user, string pwd, HttpContext context)
        {
            vLogin vl = new vLogin();
            vl.UserName = user;
            vl.Password = pwd;
            var ret = UserMag.Login(vl);
            switch (ret)
            {
                case RetUserLogin.Success:
                    context.Session["User"] = UserMag.GetUserTicket(user);
                    return "0";
                case RetUserLogin.User_Not_Exists:
                    return "-1001";
                case RetUserLogin.User_Pwd_Not_Match:
                    return "-1002";
                default:
                    return "-1003";
            }
        }

        private void Render(string ct, HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write(ct);
            context.Response.End();
        }
    }
}